const Gdk       = imports.gi.Gdk;
const GdkPixbuf = imports.gi.GdkPixbuf;
const GLib      = imports.gi.GLib;
const Gtk       = imports.gi.Gtk;
const Lang      = imports.lang;
const Octopus   = imports.gi.Octopus;

function start() {
	Gtk.init (null);
	window.global = Octopus.Global.get ();

	this.applicationWindow = new Gtk.Window({ type: Gtk.WindowType.TOPLEVEL });
	this.applicationWindow.connect ('destroy', Lang.bind(this, function () {
		Gtk.main_quit ();
	}));

	//application icon
	try {
		let iconfile = GLib.build_filenamev ([global.data_path, "octopus-48.png"]);
		this.applicationWindow.icon =  GdkPixbuf.Pixbuf.new_from_file (iconfile);
	} catch (e) {
		print ("ERROR loading application icon: " + e.message);
	}
	//gtk css
	let provider = new Gtk.CssProvider ();
	let display = Gdk.Display.get_default ();
	let screen = display.get_default_screen ();
	let style = this.applicationWindow.get_style_context ();
	style.add_provider_for_screen (screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
	try {
		//requires gtk-css file at index 0
		provider.load_from_path (global.css_files_get (0));
	} catch (e) {
		print ("ERROR loading css file: " + e.message);
	}

	//content
	this.grid = new Gtk.Grid ();
	this.applicationWindow.add (this.grid);
	this.albumArt = new Gtk.Image ({ name: 'album-art' });
	this.grid.attach (this.albumArt, 0, 0, 1, 2);
	this.title = new Gtk.Label ({ name: 'title' });
	this.grid.attach (this.title, 1, 0, 1, 1);
	this.artist = new Gtk.Label ({ name: 'artist' });
	this.grid.attach (this.artist, 1, 1, 1, 1);
	this.duration = new Gtk.Label ({ name: 'duration' });
	this.grid.attach (this.duration, 2, 0, 1, 2);

	global.get_playback ().connect ('medialib_info_changed', Lang.bind (this, this.on_medialib_info_changed));
	global.get_playback ().load_playback ();

	this.applicationWindow.show_all();
	Gtk.main ();
}

function on_medialib_info_changed (/*Playback*/ playback_model) {
	try {
		let filename = GLib.build_filenamev ([global.bindata_path, playback_model.picture_front]);
		var unscaled = GdkPixbuf.Pixbuf.new_from_file (filename);
		var pixbuf = unscaled.scale_simple (30, 30, /*GdkPixbuf.InterpType.bilinear*/ 2);
		this.albumArt.set_from_pixbuf (pixbuf);
	} catch (e) {
		print ("ERROR loading albumart: " + e.message);
	}
	this.title.label    = playback_model.title;
	this.duration.label = Octopus.utils_format_duration (playback_model.duration);
	this.artist.label   = playback_model.artist;
}
